package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.iot.IotMsgNotifyData;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备数据Service业务层处理
 * 
 * @author xiecong
 * @date 2025-06-02
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = Page.of(dto.getPageNum(), dto.getPageSize());
        Page<DeviceData> pageInfo = lambdaQuery().eq(StringUtils.hasText(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.hasText(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .ge(dto.getStartTime() != null, DeviceData::getAlarmTime, dto.getStartTime())
                .le(dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getEndTime()).page(page);
        return getPageInfo(pageInfo);
    }

    /**
     * 封装分页对象
     * @param pageInfo
     * @return
     */
    @NotNull
    private TableDataInfo<DeviceData> getPageInfo(Page<DeviceData> pageInfo) {
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getRecords());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void insertBatchDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 判断设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, deviceId));
        if (device == null) {
            log.error("设备不存在，iotId:{}", deviceId);
            return;
        }
        // 插入设备数据
         iotMsgNotifyData.getBody().getServices().forEach(s -> {
             Map<String, Object> properties = s.getProperties();
             /**
              *  "properties": {
              *             "BodyTemp": 1,
              *             "HeartRate": 87.6276,
              *             "xueyang": 93.12909,
              *             "BatteryPercentage": 6.9553375
              *           }
              */
             if(Collections.isEmpty(properties)){
                 return;
             }
             // 处理数据上报时间
             LocalDateTime eventTime = LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
             //日期时区转换, 当前所在的时区
             LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                     // 转时区,获取系统中的时区
                     .withZoneSameInstant(ZoneId.systemDefault())
                     .toLocalDateTime();
             List<DeviceData> deviceDataList = properties.entrySet().stream().map(p -> {
                 DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                 deviceData.setId(null);
                 deviceData.setFunctionId(p.getKey());
                 deviceData.setAccessLocation(device.getRemark());
                 deviceData.setDataValue(p.getValue() + "");
                 deviceData.setAlarmTime(alarmTime);
                 deviceData.setCreateTime(null);
                 deviceData.setUpdateTime(null);
                 deviceData.setCreateBy(null);
                 deviceData.setUpdateBy(null);
                 return deviceData;
             }).collect(Collectors.toList());
             saveBatch(deviceDataList);
             redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(deviceDataList));
         });
    }
}
